package com.i8office.android.zhihuixinwu.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.cyan.tools.annotation.ActivityFragmentInject;
import com.cyan.tools.base.BaseActivity;
import com.cyan.tools.base.RecyclerArrayAdapter;
import com.cyan.tools.util.RxBus;
import com.cyan.tools.widget.ItemDecoration;
import com.example.menhoo.toollibrary.common.assist.IMEHelper;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.i8office.android.zhihuixinwu.R;
import com.i8office.android.zhihuixinwu.adapter.PeopleAdapter;
import com.i8office.android.zhihuixinwu.adapter.SendAdapter;
import com.i8office.android.zhihuixinwu.bean.Mode;
import com.i8office.android.zhihuixinwu.bean.NotifyTarget;
import com.i8office.android.zhihuixinwu.bean.People;
import com.i8office.android.zhihuixinwu.bean.Send;
import com.i8office.android.zhihuixinwu.bean.SendInfo;
import com.i8office.android.zhihuixinwu.bean.SendTarget;
import com.i8office.android.zhihuixinwu.bean.WorkSheet;
import com.i8office.android.zhihuixinwu.module.contract.StaffContract;
import com.i8office.android.zhihuixinwu.module.presenter.StaffPresenter;
import com.i8office.android.zhihuixinwu.ui.dep.OfficeNewActivity;
import com.socks.library.KLog;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.Main;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import tools.ToastUtil;
import view.ThreePointLoadingView;

@ActivityFragmentInject(
        contentViewId = R.layout.activity_staff,
        toolbarTitle = R.string.select_staff,
        menuId = R.menu.confirm
)
public class StaffActivity extends BaseActivity<StaffContract.Presenter> implements StaffContract.View, TextView.OnEditorActionListener {
    WorkSheet workSheet;
    @BindView(R.id.steps)
    RecyclerView steps;
    @BindView(R.id.hint)
    TextView hint;
    @BindView(R.id.drawerLayout)
    DrawerLayout drawerLayout;
    @BindView(R.id.keyword)
    EditText keyword;
    @BindView(R.id.peopleLayout)
    LinearLayout peopleLayout;
    @BindView(R.id.staffs)
    RecyclerView staffs;
    @BindView(R.id.loading)
    ThreePointLoadingView loading;
    private SendAdapter sendAdapter;
    private PeopleAdapter peopleAdapter;
    Observable<Mode> observable;
    Disposable disposable;
    Mode mode;
    SendInfo sendInfo;
    String memo;
    boolean isEnd = false;
    boolean isLoading = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        memo = getIntent().getStringExtra("memo");
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f) //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                .init();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mPresenter = new StaffPresenter(this);
        workSheet = (WorkSheet) getIntent().getSerializableExtra("workSheet");
        sendAdapter = new SendAdapter(this);
        steps.setLayoutManager(new LinearLayoutManager(this));
        steps.addItemDecoration(new ItemDecoration(this, 1));
        steps.setAdapter(sendAdapter);
        peopleAdapter = new PeopleAdapter(this);
        staffs.setLayoutManager(new LinearLayoutManager(this));
        staffs.addItemDecoration(new ItemDecoration(this, 1));
        staffs.setAdapter(peopleAdapter);
        keyword.setOnEditorActionListener(this);
        peopleAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                People item = peopleAdapter.getItem(position);
                if (peopleAdapter.isIs_single()) {
                    if (peopleAdapter.getStaffs().contains(item))
                        peopleAdapter.getStaffs().remove(peopleAdapter.getItem(position));
                    else {
                        peopleAdapter.getStaffs().clear();
                        peopleAdapter.getStaffs().add(item);
                    }
                    peopleAdapter.notifyDataSetChanged();
                } else {
                    if (peopleAdapter.getStaffs().contains(item))
                        peopleAdapter.getStaffs().remove(item);
                    else peopleAdapter.getStaffs().add(item);
                    peopleAdapter.notifyDataSetChanged();
                }
            }
        });
        observable = RxBus.get().register("add_staff", Mode.class);
        disposable = observable.subscribe(new Consumer<Mode>() {
            @Override
            public void accept(final Mode newMode) throws Exception {
                if (sendInfo.getCurrentNode().getSendMode() == 1
                        && mode != null
                        && newMode.getPosition() != mode.getPosition()
                        && !sendAdapter.getItem(mode.getPosition()).getChooseMap().isEmpty()) {
                    new MaterialDialog.Builder(StaffActivity.this)
                            .content(R.string.send_mode_tips)
                            .positiveText(R.string.confirm)
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    sendAdapter.getItem(StaffActivity.this.mode.getPosition()).getChooseMap().clear();
                                    sendAdapter.notifyDataSetChanged();
                                    peopleAdapter.setIs_single(newMode.getMode() == 0);
                                    StaffActivity.this.mode = newMode;
                                    List<People> isCanChoosePeoples = sendAdapter.getItem(newMode.getPosition()).getHandlerList();
                                    if (isCanChoosePeoples != null && isCanChoosePeoples.size() > 0) {
                                        keyword.setEnabled(false);
                                        peopleAdapter.addAll(isCanChoosePeoples);
                                    } else {
                                        keyword.setEnabled(true);
                                    }
                                    drawerLayout.openDrawer(Gravity.RIGHT);
                                }
                            })
                            .negativeText(R.string.cancel)
                            .onNegative(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    dialog.cancel();
                                }
                            })
                            .show();
                    return;
                }
                peopleAdapter.setIs_single(newMode.getMode() == 0);
                StaffActivity.this.mode = newMode;
                List<People> isCanChoosePeoples = sendAdapter.getItem(newMode.getPosition()).getHandlerList();
                if (isCanChoosePeoples != null && isCanChoosePeoples.size() > 0) {
                    keyword.setEnabled(false);
                    peopleAdapter.addAll(isCanChoosePeoples);
                } else {
                    keyword.setEnabled(true);
                    searchPeople();
                }
                drawerLayout.openDrawer(Gravity.RIGHT);
            }
        });

        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                keyword.setText("");
                peopleAdapter.getStaffs().clear();
                peopleAdapter.clear();
                IMEHelper.hideIME(StaffActivity.this, true);
            }

            @Override
            public void onDrawerStateChanged(int newState) {
            }
        });
        progressDialog = ProgressDialog.show(this, "", getString(R.string.loading));
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(true);
        getSendInfo();
    }

    @Override
    public void showResults(SendInfo sendInfo) {
        hideDialogProgress();
        this.sendInfo = sendInfo;
        isEnd = sendInfo.getCurrentNode().getSendMode() == 0 && sendInfo.getSendList().size() == 1 && sendInfo.getSendList().get(0).getHandlerList().size() == 0;
        sendAdapter.setEnd(isEnd);
        if ((sendInfo.getSendList() == null || sendInfo.getSendList().isEmpty()) && (sendInfo.getBackList() == null || sendInfo.getBackList().isEmpty())) {
            steps.setVisibility(View.GONE);
            hint.setVisibility(View.VISIBLE);
        } else {
            steps.setVisibility(View.VISIBLE);
            hint.setVisibility(View.GONE);
            if (sendInfo.getSendList() != null)
                sendAdapter.addAll(sendInfo.getSendList());
        }
    }

    @Override
    public void showPeoples(ArrayList<People> peoples) {
        peopleAdapter.getStaffs().clear();
        peopleAdapter.getData().clear();
        peopleAdapter.addAll(peoples);
    }

    @Override
    public void checkResult() {
        Map<String, String> map = new HashMap<>();
        map.put("mid", workSheet.getMid());
        map.put("nid", workSheet.getNid());
        map.put("memo", memo);
        map.put("memoAtts", new JSONArray().toString());
        List<Send> sendList = sendAdapter.getData();
        List<SendTarget> targets = new ArrayList<>();
        if (sendList != null) {
            for (Send send : sendList) {
                if (isEnd) {
                    targets.add(new SendTarget(send.getNode().getNodeKey(), "", ""));
                } else {
                    for (People p : send.getChooseList()) {
                        targets.add(new SendTarget(send.getNode().getNodeKey(), p.getEmplID(), send.getNode().getMultiHandleMode() == 0 ? "" : "multi"));
                    }
                }
            }
        }
        String target = new Gson().toJson(targets);
        KLog.e("target:" + target);
        map.put("targets", target);
        mPresenter.submit(map);
    }

    @Override
    public void submitResult() {
        Map<String, String> params = new HashMap<>();
        params.put("mid", workSheet.getMid());
        params.put("sendsucc", "1");
        mPresenter.open(params);


        //提交成功之后发送通知
        Map<String, String> params1 = new HashMap<>();
        params1.put("mid", workSheet.getMid());
        params1.put("nodekey", workSheet.getNid());
        List<Send> sendList = sendAdapter.getData();
        List<NotifyTarget> targets = new ArrayList<>();
        if (sendList != null) {
            for (Send send : sendList) {
                NotifyTarget notifyTarget = new NotifyTarget();
                notifyTarget.nid = send.getNode().getNodeKey();
                StringBuffer sb = new StringBuffer();
                if (!isEnd) {
                    for (People p : send.getChooseList()) {
                        sb.append(p.getEmplID() + ",");
                    }
                }
                if (TextUtils.isEmpty(sb.toString())) {
                    notifyTarget.empl = sb.toString();
                } else {
                    notifyTarget.empl = sb.toString().substring(0, sb.length() - 1);
                }
                targets.add(notifyTarget);
            }
        }
        String nlist = new Gson().toJson(targets);
        params1.put("nlist", nlist);
        mPresenter.sendNotification(params1);
    }

    @Override
    public void openResult() {
        ToastUtil.showCenter(this, R.string.submit_success);
        RxBus.get().post("submitSuccess", "");
        if (DetailActivity.from.equals("office")) {
            Intent intent = new Intent(this, OfficeActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }  else if(DetailActivity.from.equals("office_new")){
            Intent intent = new Intent(this, OfficeNewActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }else if (DetailActivity.from.equals("main")) {
            Intent intent = new Intent(this, Main.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        DetailActivity.from = "";
    }

    @Override
    public void requestError() {
        isLoading = false;
        hideDialogProgress();
    }

    @Override
    public void showProgress() {
    }

    @Override
    public void hideProgress() {
        loading.stop();
    }
    private void hideDialogProgress(){
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.cancel();
        }
    }
    @OnClick(R.id.confirm)
    public void onViewClicked() {
        sendAdapter.getItem(mode.getPosition()).addChooseList(peopleAdapter.getStaffs());
        sendAdapter.notifyDataSetChanged();
        drawerLayout.closeDrawers();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (disposable != null && !disposable.isDisposed()) disposable.dispose();
        if (observable != null) RxBus.get().unregister("add_staff", observable);
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
            IMEHelper.hideIME(this, true);
            searchPeople();
            return true;
        }
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
//                if (this.getClass() != MainActivity.class)
                finish();
                break;
            case R.id.add://确定
                if(isLoading){
                    return false;
                }
                isLoading = true;
                progressDialog.show();
                Map<String, String> map = new HashMap<>();
                map.put("mid", workSheet.getMid());
                map.put("nid", workSheet.getNid());
                mPresenter.checkBeforeSubmit(map);
                break;
            default:
                break;
        }
        return false;
    }

    private void searchPeople() {
        loading.play();
        String keywordStr = keyword.getText().toString().trim();
        Map<String, String> map1 = new HashMap<>();
        map1.put("dept", "0");
        map1.put("keyword", keywordStr);
        map1.put("begin", "1");
        map1.put("end", "50");
        mPresenter.searchPeople(map1);
    }

    public void getSendInfo() {
        progressDialog.show();
        Map<String, String> map = new HashMap<>();
        map.put("mid", workSheet.getMid());
        map.put("nid", workSheet.getNid());
        mPresenter.getSendInfo(map);
    }
}
